# -*- coding:utf-8 -*-
import os
import socket
import requests


def saveImage(url,path):
    r = requests.get(url)
    file_name = get_file_name(r.url, r.headers)
    if not os.path.exists(path) :
        os.makedirs(path)
    with open(path+file_name, 'wb') as f:
        f.write(r.content)
    print(file_name)
    return file_name


def get_file_name(url, headers):
    filename = ''
    if 'Content-Disposition' in headers and headers['Content-Disposition']:
        disposition_split = headers['Content-Disposition'].split(';')
        if len(disposition_split) > 1:
            if disposition_split[1].strip().lower().startswith('filename='):
                file_name = disposition_split[1].split('=')
                if len(file_name) > 1:
                    filename = unquote(file_name[1])
    if not filename and os.path.basename(url):
        filename = os.path.basename(url).split("?")[0]
    if not filename:
        return time.time()
    return filename

if __name__ == "__main__":
    mjx()
